import dayjs from "dayjs";
import { addNum, mulNum, subNum, mask } from "shiptools";
// import drawQrcode from '../../utils/qrcode'
var QR = require("../../utils/qrcode.js");
import { cleanOrderData, invoiceFactory, canRefundTicket } from "./main";
import {
  getOrderApi,
  getCityLinePortApi,
  getRefundRecodeApi,
  getCanRefundConfApi,
  getInvoiceDetailNewApi,
  feedBackApi,
  cancelShipOrderApi,
  getOrderStatusApi,
  noticeSomeoneTicketOutApi,
  refundTicketApi,
  getServiceNoticeApi,
} from "../../api/index";

import {
  SHIP_PASSENGER_TYPE_ORDER,
  SHIP_CERT_TYPE,
  WEEK_ENUM,
  channel,
  APPROVE_DESC,
  SHIP_SERVICE_AGREEMENT_HTML,
  TRACER_PAGES,
  PRODUCT_CODE,
} from "../../utils/constants";
let eventTracer = require("../../utils/eventtracer.js");
import {
  Logger,
  CountDown,
  asyncToast,
  showDayName,
  setPage,
  queryString,
  setEvent,
} from "../../utils/index";
const logger = new Logger();
const pageName = TRACER_PAGES["order"];

// 实例化一个定时器
const countDown = new CountDown();

let animationTimer = null;
let requestTimer = null;

let rushOutimer = null;

let interval = null;
// plugin/pages/order/index.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    query: {},
    orderTitle: "",

    countDownTime: 0,
    minute: 0,
    second: 0,

    isPriceListOpened: false,

    percent: 0,
    orderDetail: {
      orderStateName: "",
    },
    qrCodePassengerList: [],
    isShowQrCode: false,

    locationOpened: false,
    fetchingTicketAddress: "",
    portAddress: "",

    hasAlterNative: false,

    // 乘客信息和票相关
    departureDate: "",
    departureRecentDayName: "",
    departureDay: "",
    voyageType: "",
    contactInfoList: [],
    isOnlyTruck: false,
    cardNoForTruck: "",

    backTripDate: "",
    backTripRecentDayName: "",
    backTripDay: "",
    ticketList: [],
    passengersList: [],

    isPassengerDialogOpened: false,

    showRefundProgress: false,
    refundProgressTotalPrice: 0,
    refundRecordRes: [],

    qrCodePath: [],
    currentSwiper: 0,

    isTicketDialog: false,

    // 退票相关
    refundMsg: "",
    canRefund: false,

    ticketOutDate: "",

    // 备选
    isAlternateOpened: false,

    isCancelWindowOpened: false, // 取消订单弹窗是否打开
    isDeleteServiceWindowOpened: false,
    cancelReasonSelectedIndex: -1, // 已选取消原因的索引值
    cancelReasonContent: "",
    cancelReasonsList: [
      // 取消订单原因列表
      {
        id: 1,
        title: "余额不足，无法支付",
      },
      {
        id: 2,
        title: "信息填写错误",
      },
      {
        id: 3,
        title: "行程临时有变，不需要这笔订单了",
      },
      {
        id: 4,
        title: "不小心购买了优选服务",
      },
      {
        id: 5,
        title: "我只是来看看，不想购买",
      },
      {
        id: 6,
        title: "其他原因",
      },
    ],

    // 发票相关
    invoiceDetail: {},
    invoiceExpiryDayCount: 0,
    invoiceOperateName: "",

    isRushOutBtnDisabled: false,
    countDownTimeForRushOut: 5,

    payargs: {
      fee: 1,
      paymentArgs: {
        serialId: "",
      },
    },

    isFirstLoad: true,

    footNotices: [1],
    approveDesc: APPROVE_DESC,

    serviceNoticeOpen: false,
    independent: false,
    currentNotice: {},
    serviceNotices: [],

    
    vechileInfo: [],

    vstValue: '',
    vstWithStatus: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.init(options);

    eventTracer.setSessionId();
    setPage(pageName + "?" + queryString(options), PRODUCT_CODE);
  },

  onShow: function () {
    const options = this.data.query;
    const isFirstLoad = this.data.isFirstLoad;
    if (!isFirstLoad) {
      this.init(options);
    }
  },

  onPullDownRefresh: function () {
    wx.showNavigationBarLoading();
    const query = this.data.query;
    this.getOrder(query).then(() => {
      wx.hideNavigationBarLoading(); //完成停止加载图标
      wx.stopPullDownRefresh();
    });
  },
  init: function (query) {
    this.setData({
      query,
    });
    this.getOrder(query);
  },

  getOrder: function ({ serialId }) {
    const that = this;
    if (!serialId) return;
    const percent = that.data.percent;
    return getOrderApi({ serialId }).then((response) => {
      if(!response) return
      let orderDetail = cleanOrderData(response);

      // FIXME: test
      // orderDetail.orderStateName = '已出票'

      orderDetail.serviceList = that.getServiceList(orderDetail);
      orderDetail.orderInfoList = that.getOrderInfoList(orderDetail);

      // 备选时段 数据设置
      let _reserveTimeSlot = "";
      if (orderDetail.reserveTimeSlot) {
        _reserveTimeSlot = orderDetail.reserveTimeSlot;
        orderDetail.backupTime = that.calculateAlterTime(
          _reserveTimeSlot,
          orderDetail.departureInfo.departureDateTime
        );
      }

      that.getCityLinePort(orderDetail);

      //   退款进度
      that.getRefundRecode(orderDetail);

      that.getCanRefundConf(orderDetail);

      that.getServiceNotice(orderDetail);

      let qrCodePassengerList = that.getQrCodePassengerList(orderDetail);

      const isShowQrCode =
        orderDetail.orderStateName === "已出票" &&
        orderDetail.qrCodeUsage !== 0 &&
        (orderDetail.qrCode || qrCodePassengerList.length > 0); // 是否展示船票二维码

      const orderTitle = that.setTicketState(orderDetail);

      const locationOpened =
        orderDetail.orderStateName === "已出票" &&
        (qrCodePassengerList.length > 0 || !!orderDetail.qrCode);

      if (orderDetail.orderStateName === "已支付" && percent === 0) {
        that.doProgress(orderDetail);
      }

      let ticketOutDate = "";
      if (
        orderDetail.orderStateName === "已支付" ||
        orderDetail.orderStateName === "待出票"
      ) {
        ticketOutDate = dayjs(orderDetail.departureInfo.departureDateTime)
          .subtract(subNum(orderDetail.preSaleDays, 1), "day")
          .format("MM月DD日");
      }

      if (orderDetail.orderStateName === "待支付") {
        const createTime = orderDetail.createTime;
        const serverTime = orderDetail.serverTime;
        that.payCountDown(serverTime, createTime);
      } else {
        countDown.clearTimer();
      }

      that.getInvoiceDetail(orderDetail);

      const hasAlterNative = that.hasAlternateContent(orderDetail);

      const departureInfo = orderDetail.departureInfo;
      const isRoundTrip = orderDetail.isRoundTrip;
      const backTripInfo = orderDetail.backTripInfo;
      const vechileInfo = orderDetail.shipItemVehicle;
      let passengersList = []; // 格式化后的乘客列表
      let ticketList = []; // 船票种类列表
      if (orderDetail.passengerList) {
        passengersList = this.getFormatPassengerList(orderDetail.passengerList); // 格式化后的乘客列表
        ticketList = this.getTicketList(orderDetail.passengerList);
      }
      const departureDate =
        departureInfo && dayjs(departureInfo.date).format("MM-DD"); // 去程日期
      const departureRecentDayName =
        departureInfo &&
        showDayName(departureInfo.date, !orderDetail.isSerialVoyage); // 显示今天、明天或后天
      const departureDay = departureInfo && this.showDay(departureInfo.date); // 去程周几
      let backTripDate = "";
      let backTripRecentDayName = "";
      let backTripDay = "";
      if (isRoundTrip) {
        backTripDate = dayjs(backTripInfo.date).format("MM-DD"); // 返程日期
        backTripRecentDayName = showDayName(
          backTripInfo.date,
          !orderDetail.isSerialVoyage
        ); // 显示今天、明天或后天
        backTripDay = this.showDay(backTripInfo.date); // 返程周几
      }
      const voyageType = this.getVoyageType(orderDetail);
      const contactInfoList = this.getContactInfoList(orderDetail); // 联系信息列表
      // 是否只购买货车
      const isOnlyTruck =
        (passengersList.length === 0 ||
          (passengersList[0] && !passengersList[0].name)) &&
        vechileInfo &&
        vechileInfo.length > 0 &&
        orderDetail.supplierId === 259;
      const cardNoForTruck =
        orderDetail.contactCertNo && mask(orderDetail.contactCertNo, 6, 14);

      if (orderDetail.qrCode) {
        that.createQrCode(orderDetail.qrCode, "orderQrcode", 120, 120);
      }
      if (qrCodePassengerList.length > 0) {
        qrCodePassengerList.forEach((item) => {
          that.createQrCode(
            item.qrCode,
            `passengerQrcode_${item.qrCode}`,
            120,
            120
          );
        });
      }

      let notDeletedServiceList = [];
      if (orderDetail && orderDetail.serviceList) {
        notDeletedServiceList = orderDetail.serviceList.filter(
          (item) => !item.isDeleted
        );
      }

      // const payArg = {
      //   fee: mulNum(orderDetail.totalAmount, 100),
      //   paymentArgs: {
      //     serialId: orderDetail.serialId,
      //   },
      // };
      const vstValue = `^航线名称:${orderDetail.departure}-${orderDetail.destination}^出发港口:${orderDetail.departureInfo.departurePort}^到达港口:${orderDetail.departureInfo.arrivalPort}^`
      const vstWithStatus = `^航线名称:${orderDetail.departure}-${orderDetail.destination}^出发港口:${orderDetail.departureInfo.departurePort}^到达港口:${orderDetail.departureInfo.arrivalPort}^订单状态:${orderDetail.orderStateName}`

      that.setData({
        isFirstLoad: false,
        orderDetail,
        qrCodePassengerList,
        isShowQrCode,
        orderTitle,
        locationOpened,
        hasAlterNative,

        departureDate,
        departureRecentDayName,
        departureDay,
        voyageType,
        contactInfoList,
        isOnlyTruck,
        cardNoForTruck,

        backTripDate,
        backTripRecentDayName,
        backTripDay,

        ticketList,
        passengersList,

        ticketOutDate,

        notDeletedServiceList,

        payargs: {
          fee: mulNum(orderDetail.totalAmount, 100),
          paymentArgs: {
            serialId: orderDetail.serialId,
          },
        },

        vechileInfo,

        vstValue,
        vstWithStatus
      });

      setEvent('订单详情页', 'XQ09', vstWithStatus)

      return orderDetail;
    });
  },

  // 获取购票须知
  getServiceNotice: function ({ lineId, departureInfo, passengerList }) {
    const that = this;

    let seatName = ''
    if(passengerList && passengerList.length > 0) {
      seatName = passengerList[0].seatName
    }
    getServiceNoticeApi({
      LineId: lineId,
      DepartDate: departureInfo.departureDateTime,
      SeatName: seatName,
    }).then((response) => {
      if (!response || response.length <= 0) {
        return;
      }

      that.setData({
        serviceNotices: response,
      });
    });
  },
  /**
   * 格式化时间
   * @param {Number} time 待格式化的时间，单位秒
   * @returns {Object} 包含分钟和秒的对象，例如{minute: 1, second: 30}
   */
  _formatTime(time) {
    const minute = Math.floor(time / 60);
    const second = time % 60;
    return {
      minute,
      second,
    };
  },
  /**
   * 支付倒计时
   * @param {String | Date} currentTime 当前时间
   * @param {String | Date} createTime 创建时间
   */
  payCountDown: function (currentTime, createTime) {
    const that = this;
    const start = 20 * 60; // 倒计时初始值，20分钟
    const timePassed = dayjs(currentTime).diff(dayjs(createTime), "second");
    const timeLeft = start - timePassed;
    if (timeLeft > 0) {
      countDown
        .timing(timeLeft, (val) => {
          const { minute, second } = that._formatTime(val);
          that.setData({
            countDownTime: val,
            minute,
            second,
          });
        })
        .then(() => {
          that.updateOrderStatus("已取消");
        });
    }
  },

  updateOrderStatus: function () {
    const orderDetail = this.data.orderDetail;
    this.getOrder(orderDetail);
  },
  handlePayConfirm: function () {

    const vstValue = this.data.vstValue
    setEvent('订单详情页', 'XQ02', vstValue)

  },
  repay: function () {},

  createQrCode: function (qrcode, id, cavW, cavH) {
    const that = this;
    that.setData(
      {
        qrCodePath: [],
      },
      () => {
        //调用插件中的draw方法，绘制二维码图片
        QR.qrApi.draw(qrcode, id, cavW, cavH).then((canvas) => {
          //二维码生成之后调用canvasToTempImage();延迟3s，否则获取图片路径为空
          that.canvasToTempImage(canvas);
        });
      }
    );
  },

  // 支付成功的回调接口
  paymentSuccess: function (e) {
    const { paymentArgs } = this.data.payargs;
    // this.goOrderDetailPage(paymentArgs)
    this.getOrder(paymentArgs);
    // e.detail.extraData.timeStamp // 用 extraData 传递数据，详见下面功能页函数代码
  },

  // 支付失败的回调接口
  paymentFailed: function (e) {
    const { paymentArgs } = this.data.payargs;
    this.getOrder(paymentArgs);
  },

  //获取临时缓存照片路径，存入data中
  canvasToTempImage: function (id) {
    const that = this;
    wx.canvasToTempFilePath({
      canvasId: id,
      success: function (res) {
        const tempFilePath = res.tempFilePath;
        let qrCodePath = that.data.qrCodePath;
        qrCodePath.push(tempFilePath);
        that.setData({
          qrCodePath,
        });
      },
    });
  },

  handleCanvarToImg(id) {
    const that = this;
    wx.canvasToTempFilePath({
      width: 1000,
      height: 1000,
      // destWidth: 100,
      // destHeight: 100,
      canvasId: id,
      success(res) {
        const path = res.tempFilePath;
        let qrCodePath = that.data.qrCodePath;

        qrCodePath.push(path);
        that.setData({
          qrCodePath,
        });
      },
    });
  },

  getCityLinePort: function ({ departure, destination, departureInfo }) {
    const that = this;
    // 获取城市港口列表
    getCityLinePortApi({
      DepartCity: departure,
      ArriveCity: destination,
    }).then((response) => {
      if (response.status !== 200) {
        logger.tips("网络错误");
        return;
      }
      if (!response.data || response.data.Code !== 10000) {
        logger.tips("请求失败或者没有数据");
        return;
      }
      const data = response.data.Data;
      // 查找所选班次的港口信息
      const portInfo = data.find(
        (item) => item.PortName === departureInfo.departurePort
      );

      const fetchingTicketAddress =
        (portInfo && portInfo.PortTicketPoint) || "--";
      const portAddress = (portInfo && portInfo.PortAddress) || "--";

      that.setData({
        fetchingTicketAddress,
        portAddress,
      });
    });
  },

  setTicketState: function (orderDetail) {
    let title = "";
    switch (orderDetail.orderStateName) {
      case "待支付": {
        title = "待支付";

        break;
      }
      case "已支付": {
        title = "出票中";

        break;
      }
      case "待出票": {
        title = "待出票";
        break;
      }
      case "已出票": {
        title = "已出票";

        break;
      }
      case "改签中": {
        title = "改签中...";

        break;
      }
      case "改签成功": {
        title = "改签成功";

        break;
      }
      case "出票失败": {
        title = "出票失败";

        break;
      }
      case "退票中": {
        title = "退票中...";

        break;
      }
      case "退票失败": {
        title = "退票失败";

        break;
      }
      case "退款中": {
        title = "退款中";

        break;
      }
      case "已退款": {
        title = "已退款";

        break;
      }
      case "已取消": {
        title = "已取消";

        break;
      }
      default: {
        title = "未知订单状态";
        break;
      }
    }
    return title;
  },

  //   进度条
  doProgress: function (orderDetail) {
    const that = this;
    const serverTime = orderDetail.serverTime;
    const createTime = orderDetail.payBackTime;
    const timeDiff = dayjs(serverTime).diff(dayjs(createTime), "second");
    const progressTime = Math.round(timeDiff);
    // const percent = timeDiff >= 6 ? 96 : divNum(mulNum(parseInt(timeDiff), 100), 75) // 初始化进度条百分比

    let startProgress = 0;
    if (progressTime > 25 && 72 > progressTime) {
      startProgress = 25 + progressTime;
      // that.animation.width('96%').step({ duration: (96-startProgress)*1000 })
    } else if (progressTime <= 25) {
      startProgress = progressTime * 2;
      // that.animation.width('50%').step({ duration: (50-startProgress)*500 })
    } else {
      startProgress = 96;
    }

    //读条逻辑 请求订单状态逻辑
    var currentProgress = startProgress;
    if (currentProgress >= 50 && currentProgress < 96) {
      interval = setInterval(function () {
        currentProgress++;
        that.getActualProgress(currentProgress, orderDetail);
        that.setData({
          currentProgress,
        });
        if (currentProgress >= 96) {
          clearInterval(interval);
        }
      }, 1000);
    } else if (currentProgress < 50) {
      interval = setInterval(function () {
        currentProgress++;
        that.getActualProgress(currentProgress, orderDetail);
        that.setData({
          currentProgress,
        });
        if (currentProgress >= 50) {
          clearInterval(interval);
          interval = setInterval(function () {
            currentProgress++;
            that.getActualProgress(currentProgress, orderDetail);
            that.setData({
              currentProgress,
            });
            if (currentProgress >= 96) {
              clearInterval(interval);
            }
          }, 1000);
        }
      }, 500);
    }

    this.setData({
      percent: startProgress,
      currentProgress,
    });
    if (!animationTimer) {
      this.setProgress();
      // this.getActualProgress(currentProgress, orderDetail)
    }
  },

  /**
   * 设置出票进度（假的出票进度，动画）
   */
  setProgress: function () {
    const interval = 200; // 动画间隔
    animationTimer = setInterval(() => {
      const preValue = this.data.percent;
      if (preValue >= 96) {
        // 进度值超过90时，清除进度动画
        clearInterval(animationTimer);
        animationTimer = null;
      } else {
        this.setData({
          percent: addNum(preValue, 1),
        });
      }
    }, interval);
  },

  /**
   * 获取真实的进度
   */
  getActualProgress: function (progress, orderDetail) {
    const that = this;

    var requestTimeArr = [56];
    for (var i = 10; i <= 50; i = i + 10) {
      requestTimeArr.push(i);
    }
    for (var i = 61; i <= 96; i = i + 3) {
      requestTimeArr.push(i);
    }
    if (requestTimeArr.indexOf(progress) > -1) {
      const serialId = orderDetail.serialId;
      that
        .getOrderStatus(serialId)
        .then((status) => {
          debugger
          if (status !== "已支付") {
            if (interval) {
              clearInterval(interval);
            }
            that.getOrder(orderDetail);
          }
        })
        .catch((error) => {
          console.log(error);
        });
      // .then((val) => {
      //     if (val !== '已支付') { // 订单状态不是'已支付'时，清除动画和轮询
      //         if (requestTimer) {
      //             clearInterval(requestTimer)
      //             requestTimer = null
      //         }
      //         if (animationTimer) {
      //             clearInterval(animationTimer)
      //             requestTimer = null
      //         }
      //     }
      // })
    }

    // // TODO: 订单详情接口换成订单状态接口
    // const interval = 3000 // 轮询间隔
    // requestTimer = setInterval(() => {

    // }, interval)
  },

  getCanRefundConf: function ({ orderId, serialId }) {
    const that = this;
    getCanRefundConfApi({
      orderId,
      orderSerialId: serialId,
      ticketPartRefund: [],
    }).then((response) => {
      if (!response) return;
      const canRefund = canRefundTicket(response);

      that.setData({
        canRefund,
        refundRules: response,
        refundMsg: response.PreventRefundMsg,
      });
    });
  },

  getRefundRecode: function ({ serialId }) {
    const that = this;
    getRefundRecodeApi({ serialId }).then((response) => {
      let showRefundProgress = false,
        refundProgressTotalPrice = 0;
      if (response && response.length > 0) {
        showRefundProgress = true;

        response.map((item) => {
          item.RefundDoneTime = dayjs(item.RefundSuccessTime)
            .add(7, "day")
            .format("YYYY-MM-DD HH:mm");
          refundProgressTotalPrice = addNum(
            refundProgressTotalPrice,
            item.RefundAmount
          );
        });
      }
      that.setData({
        showRefundProgress,
        refundProgressTotalPrice,
        refundRecordRes: response,
      });
    });
  },

  /**
   * 生成服务列表
   * @param {Object} orderDetail 订单详情数据
   * @returns {Array} 服务列表
   */
  getServiceList: function (orderDetail) {
    const passengerCount = orderDetail.passengerList.length;
    const serviceList = [
      {
        id: 0,
        title: "船票",
        price: parseFloat(orderDetail.totalPrice),
        priceTip:
          orderDetail.shipItemVehicle && orderDetail.shipItemVehicle.length > 0
            ? "（含车票）"
            : "",
        count: 0,
        canDelete: false,
        isDeleted: false,
      },
    ];
    if (orderDetail.preferredServiceAmount && orderDetail.isFromRevenueOrder) {
      // 增值服务
      serviceList.push({
        id: 1,
        title: orderDetail.valueAddServiceName,
        price: orderDetail.preferredServiceAmount / passengerCount,
        priceTip: "",
        count: passengerCount,
        canDelete: true,
        isDeleted: false,
      });
    }
    if (orderDetail.insuranceAmount) {
      // 意外险
      const actualPassengerCount = orderDetail.isRoundTrip
        ? passengerCount * 2
        : passengerCount;
      serviceList.push({
        id: 2,
        title: "轮船意外险",
        price: orderDetail.insuranceAmount / actualPassengerCount,
        priceTip: "",
        count: actualPassengerCount,
        canDelete: true,
        isDeleted: false,
      });
    }
    if (orderDetail.changerRefundInsuranceAmount) {
      //退改、退票无忧
      serviceList.push({
        id: 3,
        title: orderDetail.isChangeOrder ? "退改无忧" : "退票无忧",
        price: orderDetail.changerRefundInsuranceAmount / passengerCount,
        priceTip: "",
        count: passengerCount,
        canDelete: true,
        isDeleted: false,
      });
    }
    if (orderDetail.vehicleInsuranceAmount) {
      // 车辆保险
      serviceList.push({
        id: 4,
        title: "船上车辆运输险",
        price: orderDetail.vehicleInsuranceAmount,
        priceTip: "",
        count: 1,
        canDelete: true,
        isDeleted: false,
      });
    }
    if (orderDetail.speedOutTicket && orderDetail.speedOutTicket.salePrice) {
      // 极速出票
      serviceList.push({
        id: 5,
        title: "极速出票",
        price: orderDetail.speedOutTicket.salePrice,
        priceTip: "",
        count: 1,
        canDelete: true,
        isDeleted: false,
      });
    }
    if (orderDetail.valueAddServiceReduceAmount) {
      // 立减优惠
      serviceList.push({
        id: 6,
        title: "立减优惠",
        price: -orderDetail.valueAddServiceReduceAmount,
        priceTip: "",
        count: 0,
        canDelete: false,
        isDeleted: false,
      });
    }
    serviceList.push({
      id: 7,
      title: "订单总额",
      price: orderDetail.totalAmount,
      priceTip: "",
      count: 0,
      canDelete: false,
      isDeleted: false,
    });
    return serviceList;
  },

  /**
   * 生成订单明细列表
   * @param {Object} orderDetail 订单详情数据
   * @returns {Array} 订单明细列表
   */
  getOrderInfoList: function (orderDetail) {
    const orderInfoList = [
      {
        title: "订单明细",
        content: `总价￥${orderDetail.totalAmount}`,
        isBold: true,
      },
    ];

    if (orderDetail.isHaveCompositeProduct > 0) {
      // 有组合产品
      const list = [];
      if (orderDetail.totalPrice) {
        list.push({
          title: `${orderDetail.departure}-${orderDetail.destination}单程票`,
          content: `￥${orderDetail.totalPrice}`,
          isBold: false,
        });
      }
      // TODO 组合产品
    } else {
      let list = [];
      if (
        orderDetail.preferredServiceAmount > 0 &&
        orderDetail.isFromRevenueOrder
      ) {
        // 增值服务项
        const valueAddItem = {
          title: orderDetail.valueAddServiceName,
          content: `￥${
            orderDetail.preferredServiceAmount + orderDetail.ticketAllPrice
          }`,
          isBold: true,
          children: [
            {
              title: "票价总额",
              content: `￥${orderDetail.ticketAllPrice}`,
              isBold: false,
            },
          ],
        };
        const passengerCount = orderDetail.passengerList.length; // 乘客数量
        orderDetail.valueAddServiceOptionList.forEach((item, index) => {
          valueAddItem.children.push({
            title: item.optionName,
            content: `￥${item.salePrice}x${passengerCount}人`,
            isBold: false,
          });
        });

        if (orderDetail.valueAddDiscountAmount > 0) {
          valueAddItem.children.push({
            title: `${orderDetail.valueAddDIscountAmountName}(${orderDetail.valueAddDiscountAmount}元)`,
            content: `-￥${orderDetail.valueAddDiscountAmount}`,
            isBold: false,
          });
        }
        list.push(valueAddItem);
      } else {
        list = [];
        if (orderDetail.ticketAllPrice) {
          list.push({
            title: "票价总额",
            content: `￥${orderDetail.ticketAllPrice}`,
            isBold: false,
          });
        }
      }
      if (orderDetail.lineServiceAmount) {
        list.push({
          title: "服务费总额",
          content: `￥${orderDetail.lineServiceAmount}`,
          isBold: false,
        });
      }
      if (orderDetail.insuranceAmount) {
        list.push({
          title: "轮船意外险",
          content: `￥${orderDetail.insuranceAmount}`,
          isBold: false,
        });
      }
      if (orderDetail.changerRefundInsuranceAmount) {
        const title = orderDetail.isChangeOrder ? "退改无忧" : "退票无忧";
        list.push({
          title,
          content: `￥${orderDetail.changerRefundInsuranceAmount}`,
          isBold: false,
        });
      }
      if (orderDetail.valueAddServiceReduceAmount) {
        list.push({
          title: `优惠立减`,
          content: `-￥${orderDetail.valueAddServiceReduceAmount}`,
          isBold: false,
        });
      }
      if (
        orderDetail.preferredServiceAmount > 0 &&
        !orderDetail.isFromRevenueOrder
      ) {
        list.push({
          title: "优选服务",
          content: `￥${orderDetail.preferredServiceAmount}`,
          isBold: false,
        });
      }
      if (
        orderDetail.speedOutTicket &&
        orderDetail.speedOutTicket.salePrice > 0
      ) {
        list.push({
          title: "极速出票",
          content: `￥${orderDetail.speedOutTicket.salePrice}`,
          isBold: false,
        });
      }
      if (orderDetail.shipRightsPackageAmount) {
        list.push({
          title: "航海家权益礼包",
          content: `￥${orderDetail.shipRightsPackageAmount}`,
          isBold: false,
        });
      }
      if (orderDetail.discountActivityAmount) {
        list.push({
          title: "优惠活动",
          content: `-￥${orderDetail.discountActivityAmount}`,
          isBold: false,
        });
      }
      if (orderDetail.shipRightsReduceCost) {
        list.push({
          title: "立减活动（权益礼包优惠）",
          content: `-￥${orderDetail.shipRightsReduceCost}`,
          isBold: false,
        });
      }
      if (orderDetail.voucherReduceAmount) {
        list.push({
          title: "抵用券优惠",
          content: `-￥${orderDetail.voucherReduceAmount}`,
          isBold: false,
        });
      }
      if (orderDetail.isGroupTicket) {
        list.push({
          title: "团体票优惠总额",
          content: `-￥${orderDetail.groupTicketPerferentailAmout}`,
          isBold: false,
        });
      }
      if (orderDetail.shipVehicleTotalPrice) {
        list.push({
          title: "车辆上船",
          content: `￥${orderDetail.shipVehicleTotalPrice}`,
          isBold: false,
        });
        orderDetail.vehicleInsuranceAmount &&
          list.push({
            title: "车辆保险",
            content: `￥${orderDetail.vehicleInsuranceAmount}`,
            isBold: false,
          });
      }

      if (orderDetail.supplierDiscountAmount) {
        list.push({
          title: "优惠减免",
          content: `-￥${orderDetail.supplierDiscountAmount}`,
          isBold: false,
        });
      }
      orderInfoList.push(...list);
    }
    return orderInfoList;
  },

  getInvoiceDetail: function (orderDetail) {
    const { supplierId, serialId } = orderDetail;
    getInvoiceDetailNewApi({
      supplierId,
      serialId,
    }).then((response) => {
      if (!response || response.status !== 200) {
        return;
      }
      if (!response.data || !response.data.isSuccess) {
        return;
      }
      const result = response.data.data;

      //   FIXME: 发票test
      //   result.SupplierInfo.InvocingType = 2
      //   result.SupplierInfo.OfflineInvoiceType = 2
      //   result.InvoicingInfo.InvoiceStatus = 0

      const _invoiceDetail = invoiceFactory(result, orderDetail);
      if(_invoiceDetail) {
        //   const invoiceStatus = invoiceDetail && invoiceDetail.invoicingInfo && invoiceDetail.invoicingInfo.invoiceStatusName
        //   const isShowTip = (invoiceOperateName === '补开发票' || invoiceOperateName === '重新申请') && invoiceExpiryDayCount > 0
        const invoiceExpiryDayCount =
          _invoiceDetail &&
          _invoiceDetail.supplierInfo &&
          _invoiceDetail.supplierInfo.invocingExpiryDayCount;

        this.setData({
          invoiceExpiryDayCount,
          invoiceOperateName: _invoiceDetail.invoiceOperateName,
          invoiceDetail: _invoiceDetail,
        });
        return _invoiceDetail;
      }
    });
  },

  // 计算 备选时段
  calculateAlterTime: function (alternativeTimeType, date) {
    let backUpTime = "";
    switch (Number(alternativeTimeType)) {
      case 0:
        let _nextDay = "";
        const afterThreeHours = dayjs(date)
          .add(1, "hour")
          .set("hour", 0)
          .set("minute", 0)
          .set("second", 0);
        const beforeHours = dayjs(date)
          .set("hour", 0)
          .set("minute", 0)
          .set("second", 0);
        const diffRes = afterThreeHours.diff(beforeHours, "day", true);
        if (1 <= diffRes) {
          _nextDay = "次日";
        }
        backUpTime = `${dayjs(date)
          .subtract(1, "hour")
          .format("HH:mm")}-${_nextDay}${dayjs(date)
          .add(1, "hour")
          .format("HH:mm")}`;
        break;
      case 1:
        let _nextDay1 = "";
        const afterThreeHours1 = dayjs(date)
          .add(3, "hour")
          .set("hour", 0)
          .set("minute", 0)
          .set("second", 0);
        const beforeHours1 = dayjs(date)
          .set("hour", 0)
          .set("minute", 0)
          .set("second", 0);
        const diffRes1 = afterThreeHours1.diff(beforeHours1, "day", true);
        if (1 <= diffRes1) {
          _nextDay1 = "次日";
        }
        backUpTime = `${dayjs(date)
          .subtract(3, "hour")
          .format("HH:mm")}-${_nextDay1}${dayjs(date)
          .add(3, "hour")
          .format("HH:mm")}`;
        break;
      case 2:
        backUpTime = "白天(08:00-18:00)";
        break;
      case 3:
        backUpTime = "全天(00:00-24:00)";
        break;
    }

    return backUpTime;
  },

  /**
   * 筛选出带有二维码的乘客列表
   * @returns {Array} 二维码乘客列表
   */
  getQrCodePassengerList: function (orderDetail) {
    let qrCodePassengerList = [];
    const title =
      orderDetail.supplierId === 131 || orderDetail.supplierId === 23
        ? "票号"
        : "取票码";
    if (orderDetail.passengerList) {
      orderDetail.passengerList.forEach((item) => {
        if (item.qrCode) {
          qrCodePassengerList.push({
            qrCode: item.qrCode,
            seatNo: item.seatNo,
            name: item.name,
            ticketNo: item.ticketNo,
            isReturn: false,
            title,
          });
        }
        if (item.returnTicketBarCode) {
          qrCodePassengerList.push({
            qrCode: item.returnTicketBarCode,
            seatNo: item.returnSeatNo,
            name: item.name,
            ticketNo: item.returnTicketNo,
            isReturn: true,
            title,
          });
        }
      });
    }
    return qrCodePassengerList;
  },

  /**
   * 格式化周几
   * @param {String | Date} date 日期
   * @returns {String} 周几
   */
  showDay: function (date) {
    const dayjsObj = dayjs(date);
    let day = "";
    day = WEEK_ENUM[dayjsObj.day()];
    return day;
  },

  /**
   * 格式化乘客列表(用于实名制)
   * @param {Array} passengerList 乘客列表
   * @returns {Array}
   */
  getFormatPassengerList: function (passengerList) {
    if (!passengerList || passengerList.length <= 0) return;
    return passengerList.map((item) => {
      const passenger = {
        name: item.name,
        type: SHIP_PASSENGER_TYPE_ORDER[item.userType] || "成人票",
        certificateType: SHIP_CERT_TYPE[item.idType],
        certificateNumber: item.idCard,
        ticketState: item.ticketState,
        ticketStateName: item.ticketStateName,
        secondCertificateType: SHIP_CERT_TYPE[item.secondIdType],
        secondCertificateNumber: item.secondIdCard,
        carryChildInfo: item.carryChildInfo,
      };
      if (item.idType === 1) {
        // 身份证
        passenger.certificateNumber = mask(item.idCard, 6, 14);
      }
      if (item.secondIdType === 1) {
        // 身份证
        passenger.secondCertificateNumber = mask(item.secondIdCard, 6, 14);
      }
      return passenger;
    });
  },

  /**
   * 获取船票类型的列表
   * @param {Array} passengerList 乘客列表
   * @returns {Array} 船票类型列表
   */
  getTicketList: function (passengerList) {
    if (!passengerList || passengerList.length <= 0) return;
    const adultList = passengerList.filter((item) => item.userType === "1");
    const childList = passengerList.filter((item) => item.userType === "2");
    const studentList = passengerList.filter((item) => item.userType === "3");
    const oldList = passengerList.filter((item) => item.userType === "4");
    const ticketList = [];
    if (adultList.length > 0) {
      ticketList.push({
        title: "成人票",
        count: adultList.length,
      });
    }
    if (childList.length > 0) {
      ticketList.push({
        title: "儿童票",
        count: childList.length,
      });
    }
    if (studentList.length > 0) {
      ticketList.push({
        title: "学生票",
        count: studentList.length,
      });
    }
    if (oldList.length > 0) {
      ticketList.push({
        title: "长者票",
        count: oldList.length,
      });
    }
    return ticketList;
  },

  /**
   * 获取航班类型名称
   */
  getVoyageType: function (orderDetail) {
    let type = "";
    if (orderDetail.isSerialVoyage) {
      type = "流水班";
    } else {
      if (orderDetail.isHaveCompositeProduct) {
        type = "船票";
      }
    }
    return type;
  },

  /**
   * 获取联系信息列表
   * @returns {Array} 联系信息列表
   */
  getContactInfoList: function (orderDetail) {
    const contactInfoList = [];
    if (orderDetail.mobile) {
      contactInfoList.push({
        title: "联系手机：",
        content: mask(orderDetail.mobile, 3, 7),
      });
    }
    if (orderDetail.email) {
      contactInfoList.push({
        title: "电子邮箱：",
        content: orderDetail.email,
      });
    }
    if (orderDetail.southKoreaPhone) {
      contactInfoList.push({
        title: "韩国手机：",
        content: orderDetail.southKoreaPhone,
      });
    }
    if (orderDetail.southKoreaAddress) {
      contactInfoList.push({
        title: "韩国地址：",
        content: orderDetail.southKoreaAddress,
      });
    }
    return contactInfoList;
  },

  /**
   * 是否有备选信息
   * @returns {Boolean} 是否有备选信息
   */
  hasAlternateContent: function (orderDetail) {
    if (orderDetail) {
      return (
        (orderDetail.alternativeCabins &&
          orderDetail.alternativeCabins.length > 0) ||
        (orderDetail.alternativeVoyages &&
          orderDetail.alternativeVoyages.length > 0) ||
        (orderDetail.reserveTimeSlot &&
          orderDetail.reserveTimeSlot.length > 0 &&
          orderDetail.backupTime)
      );
    }
    return false;
  },

  onPageRefundProgress: function (e) {
    const serialId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `../refundProgress/index?serialId=${serialId}`,
    });

    const orderDetail = this.data.orderDetail
    setEvent('订单详情页', 'XQ36', `^订单状态:${orderDetail.orderStateName}^`)
  },

  togglePriceWindow: function () {
    const isPriceListOpened = this.data.isPriceListOpened;
    this.setData({
      isPriceListOpened: !isPriceListOpened,
    });
    const vstWithStatus = this.data.vstWithStatus
    setEvent('订单详情页', 'XQ06', vstWithStatus)
  },

  toggleContent: function () {
    const locationOpened = this.data.locationOpened;
    this.setData({
      locationOpened: !locationOpened,
    });

    const vstWithStatus = this.data.vstWithStatus
    setEvent('订单详情页', 'XQ03', vstWithStatus)
  },

  togglePassengerInfoWindow: function () {
    const isPassengerDialogOpened = this.data.isPassengerDialogOpened;
    this.setData({
      isPassengerDialogOpened: !isPassengerDialogOpened,
    });

    const vstWithStatus = this.data.vstWithStatus
    setEvent('订单详情页', 'XQ05', vstWithStatus)
  },

  toggleTicketDialog: function () {
    const isTicketDialog = this.data.isTicketDialog;
    this.setData({
      isTicketDialog: !isTicketDialog,
    });
  },
  onSwiperChange: function (e) {
    const index = e.detail.current;
    this.setData({
      currentSwiper: index,
    });
  },
  toggleAlternateWindow: function () {
    const isAlternateOpened = this.data.isAlternateOpened;
    this.setData({
      isAlternateOpened: !isAlternateOpened,
    });
  },

  prevNextSwiperHandler: function (e) {
    const type = e.currentTarget.dataset.type;
    const orderDetail = this.data.orderDetail;
    const qrCodePassengerList = this.getQrCodePassengerList(orderDetail);
    const count = type === "prev" ? -1 : type === "next" ? 1 : 0;
    const currentSwiper = this.data.currentSwiper;
    let current = addNum(currentSwiper, count);
    current =
      qrCodePassengerList.length <= current
        ? 0
        : current < 0
        ? subNum(qrCodePassengerList.length, 1)
        : current;
    this.setData({
      currentSwiper: current,
    });
  },

  /**
   * 处理取消订单、预约单、收单
   * @param {Number} type 取消类型 0: 订单; 1: 预约单; 2: 收单
   */
  handleCancelShipOrder(e) {
    const that = this;
    const type = e.currentTarget.dataset.state || 0;
    const vstValue = this.data.vstValue
    if (Number(type) === 0) {
      // 打开订单弹窗
      that.toggleCancelWindow(true);
    } else if (Number(type) === 1) {
      wx.showModal({
        title: "",
        content: "若取消预约，则无法保证第一时间为您出票，确定取消吗？",
        confirmColor: "#00C777",
        success: function (res) {
          if (res.confirm) {
            // 确定
            that.cancelOrder(type);
          }
        },
      });
    } else {
      that.cancelOrder(type);
    }
    setEvent('订单详情页', 'XQ01', vstValue)
  },

  /**
   * 取消订单、预约单、收单（发起请求）
   * @param {Number} type 取消类型 0: 订单; 1: 预约单; 2: 收单
   */
  cancelOrder: function (type) {
    const that = this;
    // const isCancelWindowOpened = this.data.isCancelWindowOpened
    // this.setData({
    //     isCancelWindowOpened: !isCancelWindowOpened
    // })
    const orderDetail = this.data.orderDetail;
    const params = {
      serialId: orderDetail.serialId,
      cancelOrderType: type,
    };
    cancelShipOrderApi(params)
      .then((result) => {
        const title = result ? "取消成功" : "取消失败";
        const icon = result ? "success" : "none";
        asyncToast({
          title,
          icon,
          mask: true,
        }).then((res) => {
          that.init(orderDetail);
        });
      })
      .catch((error) => {
        console.log(error);
      });
  },

  /**
   * 选择取消订单原因
   * @param {Number} index 所选项的索引值
   */
  selectCancelReason(e) {
    const index = e.currentTarget.dataset.index;
    const { cancelReasonsList } = this.data;

    // if (index === 3) { // 优选服务
    //     this.resetCancelWindow()
    //     this.toggleCancelWindow(false)
    //     this.openDeleteServiceWindow()
    //     return
    // }
    this.setData({
      cancelReasonSelectedIndex: index,
    });
  },

  /**
   * 重置取消订单弹窗
   */
  resetCancelWindow() {
    this.setData({
      cancelReasonSelectedIndex: -1,
      cancelReasonContent: "",
    });
  },

  /**
   * 打开或关闭取消订单弹窗
   * @param {Boolean} isCancelWindowOpened 是否打开
   */
  toggleCancelWindow(isCancelWindowOpened) {
    this.setData({
      isCancelWindowOpened,
    });
    // 关闭时，重置弹窗内容
    if (!isCancelWindowOpened) {
      this.setData({
        cancelReasonContent: "",
        cancelReasonSelectedIndex: -1,
      });
    }
  },

  toggleCloseWindow() {
    this.setData({
      isCancelWindowOpened: false,
    });
  },

  /**
   * 取消订单弹窗点击确认
   */
  cancelWindowConfirm() {
    const { cancelReasonSelectedIndex, cancelReasonContent } = this.data;
    // 校验提交内容
    if (cancelReasonSelectedIndex === -1) {
      wx.showToast({
        title: "请选择取消订单原因",
        icon: "none",
        mask: true,
      });
      return;
    }
    if (cancelReasonSelectedIndex === 5 && !cancelReasonContent.trim()) {
      // 选择其他原因，内容为空
      wx.showToast({
        title: "请输入取消原因",
        icon: "none",
        mask: true,
      });
      return;
    }
    this.submitReason({ content: cancelReasonContent, channel });
    this.cancelOrder(0);
    this.toggleCancelWindow(false);
  },

  /**
   * 反馈——提交取消原因
   * @param {String} content 取消原因
   * @param {String} channel 渠道
   * @param {Number} type 反馈类型（默认为3），0：默认；1：无班次；2：无余票；3：取消订单
   */
  submitReason({ content = "", channel, type = 3 }) {
    const params = {
      Content: content,
      Channel: channel,
      Type: type,
    };
    // return this.props.dispatch({type: 'Order/SubmitCancelReason', payload: params})
    return feedBackApi(params)
      .then((response) => {})
      .catch((error) => {});
  },

  /**
   * 更新输入的取消原因
   * @param {Any} e
   */
  handleCancelReasonChange(e) {
    const reason = e.detail;
    this.setData({
      cancelReasonContent: reason,
    });
  },

  /**
   * 取消订单弹窗点击取消
   */
  cancelWindowCancel() {
    this.cancelOrder(0);
    this.toggleCancelWindow(false);
  },

  /**
   * 打开删除服务弹窗
   */
  openDeleteServiceWindow() {
    this.setData({
      isDeleteServiceWindowOpened: true,
    });
  },

  closeDeleteServiceWindow: function () {
    this.setData({
      isDeleteServiceWindowOpened: false,
    });
  },

  rebook: function () {
    wx.navigateBack({
      delta: 100,
    });
  },

  makeOutInvoice: function () {
    const invoiceDetail = this.data.invoiceDetail;
    const orderDetail = this.data.orderDetail;
    debugger
    if (!invoiceDetail.isAllowed || !invoiceDetail.invoiceOperateName) {
      return;
    }

    wx.navigateTo({
      url: `../invoice/index?serialId=${orderDetail.serialId}&pagefrom=order`,
      success: (result) => {},
      fail: () => {},
      complete: () => {},
    });
  },

  getOrderStatus: function (serialId) {
    return getOrderStatusApi({ serialId });
  },

  noticeSupplierTicketOut: function (serialId) {
    return noticeSomeoneTicketOutApi({ serialId });
  },

  rushOut: function () {
    const that = this;
    const orderDetail = this.data.orderDetail;
    const isAlreadyRushOut = this.data.isAlreadyRushOut;
    wx.showToast({
      title: "正在刷新出票结果",
      icon: "none",
      mask: true,
    });
    const serialId = orderDetail.serialId;
    const orderId = orderDetail.orderId;
    that
      .getOrderStatus(serialId)
      .then((status) => {
        if (status === "已支付") {
          // TODO: 加上不是接口供应商的判断
          if (!isAlreadyRushOut) {
            that.noticeSupplierTicketOut(serialId).then((res) => {
              that.setData({
                isAlreadyRushOut: true,
              });
            });
          }
        } else {
          that.getOrder({ serialId });
        }
      })
      .catch((error) => {
        console.log(error);
      });
  },

  /**
   * 催出票
   */
  rushOutTicket() {
    const { isRushOutBtnDisabled } = this.data;
    if (isRushOutBtnDisabled) {
      // 催出票的按钮禁止点击，为了减少请求次数
      return;
    }
    this.setData({
      isRushOutBtnDisabled: true,
    });
    // 催出票的按钮可以点击倒计时
    rushOutimer = setInterval(() => {
      const preValue = this.data.countDownTimeForRushOut;
      const curValue = preValue - 1;
      this.setData({
        countDownTimeForRushOut: curValue,
      });
      if (curValue === 0) {
        // 倒计时为0，清除定时器，按钮置为可点击，倒计时重置
        clearInterval(rushOutimer);
        rushOutimer = null;
        this.setData({
          isRushOutBtnDisabled: false,
          countDownTimeForRushOut: 5,
        });
      }
    }, 1000);
    this.rushOut();
  },

  applyForRefund: function () {
    const that = this;
    const { orderDetail, refundRules, query } = this.data;

    if (!refundRules.CanRefund) {
      return;
    }
    // 部分退票，满足条件：1.不包含组合产品 2.退票规则支持部分退票 3.乘客数量大于1或者包含车辆 4.不在最珠海APP环境内
    if (
      !orderDetail.isHaveCompositeProduct &&
      refundRules.CanPartRefund &&
      (orderDetail.passengerList.length > 1 ||
        orderDetail.shipItemVehicle.length > 0)
    ) {
      const { serialId } = query;
      wx.navigateTo({
        url: `../partRefund/index?serialId=${serialId}`,
      });
      return;
    }
    const content = this.getRefundTip(); // 弹窗内容
    wx.showModal({
      title: "提示",
      content,
      cancelText: "点错了",
      confirmText: "申请退票",
      confirmColor: "#00C777",
      success(res) {
        let isRefundTxt = "否";
        if (res.confirm) {
          isRefundTxt = "是";
          that.refund();
        }
      },
    });
  },

  /**
   * 生成退票弹窗提示内容
   * @returns {String} 退票弹窗提示内容
   */
  getRefundTip() {
    const { orderDetail, refundRules } = this.data;
    let content = ""; // 弹框内容
    const title = orderDetail.isChangeOrder ? "退改无忧" : "退票无忧";

    // 1.退票无忧/退改无忧
    // 2.航海家权益礼包
    // 3.默认退票文案
    switch (refundRules.ReductionType) {
      case 1: {
        content = `此单已享受${title}服务，将减少退款手续费${refundRules.Compensate}%损失，具体以实际到账金额为准，退款将自动退还至支付账户`;
        if (refundRules.RefundAmt) {
          content = `此单已享受${title}服务，将减少退款手续费${refundRules.Compensate}%损失，退款金额${refundRules.RefundAmt}元，退款将自动退还至支付账户`;
        }
        break;
      }
      case 2: {
        content = `此单已享受航海家权益减免手续费服务，将减少退款手续费${refundRules.Compensate}%损失，退款金额${refundRules.RefundAmt}元，退款将自动退还至支付账户`;
        break;
      }
      default: {
        content = `订单内所有乘客都会退票， 手续费约为￥${refundRules.RefundFee}（以实际扣除为准）`;
      }
    }
    if (orderDetail.isHaveCompositeProduct) {
      // 包含组合产品
      // refundRules.CanRefund: 船票是否可退; refundRules.TicketCanRefund: 组合产品的票是否可退
      if (refundRules.CanRefund && refundRules.TicketCanRefund) {
        content = `线上退票，订单内所有船票和产品均发起退票，暂不支持部分退票（手续费约为￥${refundRules.RefundFee}，以实际扣除为准）`;
      }
      if (refundRules.CanRefund && !refundRules.TicketCanRefund) {
        content = `线上退票，仅可退订单内全员船票，暂不支持部分退票。游玩项目及门票不符合可退票规则，不支持退票。（手续费约为￥${refundRules.RefundFee}，以实际扣除为准）`;
      }
      if (!refundRules.CanRefund && refundRules.TicketCanRefund) {
        content = `线上退票，仅可退订单内全员游玩项目及门票，暂不支持部分退票。船票不符合可退票规则，不支持退票。（手续费约为￥${refundRules.RefundFee}，以实际扣除为准）`;
      }
    }
    return content;
  },

  /**
   * 退票（发起退票请求）
   */
  refund() {
    const that = this;
    const { orderDetail, refundRules, partRefundTravelType } = this.data;
    const passengerList = orderDetail.passengerList;
    const vehicleList = orderDetail.shipItemVehicle;
    let ticketPartRefund = [];
    if (passengerList && passengerList.length > 0) {
      // 去掉携童
      const passengerListWihtoutCarryChild = passengerList.filter(
        (item) => item.passengerId
      );
      ticketPartRefund = passengerListWihtoutCarryChild.map((item) => {
        return {
          TicketId: item.passengerId,
          PassengerName: item.name,
          IDCard: item.idCard,
          TicketType: 0,
          RefundState: 0,
          PartRefundTravelType: partRefundTravelType,
        };
      });
    }
    if (vehicleList && vehicleList.length > 0) {
      ticketPartRefund.push({
        TicketId: vehicleList[0].vehicleid,
        PassengerName: "",
        IDCard: vehicleList[0].no,
        TicketType: 1,
        RefundState: "",
        PartRefundTravelType: partRefundTravelType,
      });
    }
    if (!refundRules.CanPartRefund) {
      ticketPartRefund = null;
    }
    const params = {
      orderId: orderDetail.orderId,
      orderSerialId: orderDetail.serialId,
      ticketPartRefund,
    };
    refundTicketApi(params)
      .then((response) => {
        if (!response || response.status !== 200) {
          wx.showModal({
            title: "申请退票结果",
            content: "网络异常请稍后再试!",
            showCancel: false,
            confirmText: "知道了",
            confirmColor: "#00C777",
          });
          return;
        }
        if (!response.data || response.data.Code !== 10000) {
          wx.showModal({
            title: "申请退票结果",
            content: "抱歉，退票申请失败!",
            showCancel: false,
            confirmText: "知道了",
            confirmColor: "#00C777",
          });
          return;
        }
        wx.showModal({
          title: "申请退票结果",
          content: "退票申请成功，请等待系统处理",
          showCancel: false,
          confirmText: "知道了",
          confirmColor: "#00C777",
          success: function (res) {
            if (res.confirm) {
              that.getOrder(orderDetail);
            }
          },
        });
      })
      .catch((error) => {
        console.log(error);
      });
  },
  makePhoneCall: function (e) {
    const phone = e.currentTarget.dataset.phone;
    if (!phone) return;
    wx.makePhoneCall({
      phoneNumber: phone,
    });
  },

  onApproveTip: function (e) {
    const item = e.currentTarget.dataset.item;

    let title = "",
      content = "";
    switch (item) {
      case 1:
        this.onServiceNotice({});
        break;
      case 2:
        title = "船票代订服务协议";
        content = SHIP_SERVICE_AGREEMENT_HTML;
        break;
      default:
        break;
    }

    if (content && title && item !== 2) {
      this.setState({
        isDialogInsOpen: true,
        dialogContent: content,
        dialogTitle: title,
      });
    }
  },

  closeLineService: function () {
    this.setData({
      serviceNoticeOpen: false,
      independent: false,
      currentNotice: {},
    });
  },

  onServiceNotice: function (e) {
    let item = e.detail;
    if (!item || !item.NoticeType) {
      const serviceNotices = this.data.serviceNotices;
      if (!serviceNotices || serviceNotices.length <= 0) return;
      item = serviceNotices[0];
    }

    this.setData({
      serviceNoticeOpen: true,
      currentNotice: item,
    });

    // ^购取票/退改须知/服务须知/意外险/退改险^
    setEvent('订单详情页', 'XQ07', '^购取票^')
  },

  onRefundTips: function () {
    const serviceNotices = this.data.serviceNotices;
    if (!serviceNotices || serviceNotices.length <= 0) return;
    const currentNotice = serviceNotices[2];

    this.setData({
      serviceNoticeOpen: true,
      independent: true,
      currentNotice: currentNotice,
    });
  },

  toMap: function() {
    const orderDetail = this.data.orderDetail
    if(!orderDetail) return
    const departCity = orderDetail.departure
    const arriveCity = orderDetail.destination
    const departPort = orderDetail.departureInfo.departurePort
    const arrivePort = orderDetail.departureInfo.arrivalPort
    const lineId = orderDetail.lineId
    const isPort = !departCity && !arriveCity ? '1' : '0' // 是否通过港口查询
    const url = `../map/index?from=${departCity || departPort}&to=${arriveCity || arrivePort}&fromPort=${departPort}&toPort=${arrivePort}&lineId=${lineId}&isPort=${isPort}&canOrder=list`
    wx.navigateTo({
      url
    })
    
    const vstWithStatus = this.data.vstWithStatus
    setEvent('订单详情页', 'XQ04', vstWithStatus)
  }
});
